﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Power.Model;
using Power.BLL;
using DevExpress.XtraSplashScreen;
using JN.Utility;
using LogManager;
using System.IO;

namespace Power.WinUI
{
    public partial class LogOn : DevExpress.XtraEditors.XtraForm
    {
        public LogOn()
        {
            InitializeComponent();
        }

        private void LogOn_Load(object sender, EventArgs e)
        {
            //load info            
            LoadUser();
            LoadStation();
            LoadUserRefer();
            CheckDb();
        }
        private void LoadUser()
        {
            try
            {

                Sys_userBLL userBLL = new Sys_userBLL();
                DataTable dtUser = userBLL.GetAllList().Tables[0];

                txtUserID.Properties.DataSource = dtUser;
                txtUserID.Properties.DisplayMember = "user_id";
                txtUserID.Properties.ValueMember = "user_id";

                txtUserID.ItemIndex = 0;
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
                MessageBox.Show(ex.ToString());
            }
        }
        private void LoadStation()
        {
            try
            {
                Station_infoBLL stationBLL = new Station_infoBLL();
                DataTable dtSt  =stationBLL.GetAllList().Tables[0];
                txtStation.Properties.DataSource = dtSt;
                txtStation.Properties.DisplayMember = "station_name";
                txtStation.Properties.ValueMember = "station_id";

                txtStation.ItemIndex = 0;
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
                MessageBox.Show(ex.ToString());
            }
        }
        private void GetDbInfo()
        {
            try
            {                
                string constr = Power.DBUtility.PubConstant.GetConnectionString("ConnectionString");
                //string ip = constr.Substring(constr.IndexOf("server"),
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        private void LoadUserRefer()
        {
            try
            {
                string file = @"C:\Windows\\userReference.dat";
                if (File.Exists(file))
                {
                    //load file
                    Config.UserReference.Instance.LoadConfig(file);
                    Config.UserReference userRef = Config.UserReference.Instance;

                    if (!string.IsNullOrEmpty(userRef.User_id))
                    {
                        txtUserID.EditValue = userRef.User_id;
                    }
                    if (!string.IsNullOrEmpty(userRef.Station_id))
                    {
                        txtStation.EditValue = userRef.Station_id;
                    }
                }
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        private void SaveUserRefer()
        {
            try
            {
                string file = @"C:\Windows\\userReference.dat";
                Config.UserReference userRef = Config.UserReference.Instance;
                userRef.User_id = txtUserID.EditValue.ToString();
                userRef.Station_id = txtStation.EditValue.ToString();

                //
                System.Xml.Serialization.XmlSerializer serial = new System.Xml.Serialization.XmlSerializer(typeof(Config.UserReference));
                System.IO.TextWriter writer = new System.IO.StreamWriter(file);
                serial.Serialize(writer, userRef);
                writer.Close();
                writer.Dispose();
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (txtUserID.Text == "")
            {
                XtraMessageBox.Show("请选择用户名!!");
                return;
            }
            if (txtPassword.Text == "")
            {
                XtraMessageBox.Show("请输入密码!!");
                return;
            }
            if (CheckUser())
            {
                Manager.SystemStatus.Instance.Login_user = txtUserID.Text;
                Manager.SystemStatus.Instance.Station_id = txtStation.EditValue != null ? txtStation.EditValue.ToString() : "";
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                //recode log 
                DataBaseLogger.Write(DbLogType.UserLogOn, "用户:"+txtUserID.Text+"登陆系统.", Manager.SystemStatus.Instance.Station_id);
                this.Close();
            }
            else
            {
                XtraMessageBox.Show("用户名或密码错误或者此用户不具有次站点权限。请重新输入!!", "警告");
            }
        }
        private bool CheckUser()
        {
            try
            {
                
                bool ret = false;
                string pwd = Power.Common.DEncrypt.DEncrypt.Encrypt(txtPassword.Text);
                StringBuilder sql = new StringBuilder();
                sql.Append(" user_id = '" + txtUserID.Text.Trim() + "'");
                sql.Append(" and user_password = '" + pwd + "' ");
                if (txtStation.Text.Trim() != "")
                {
                    sql.Append(" and station_id ='"+txtStation.EditValue+"' ");
                }
                Sys_userBLL userBLL = new Sys_userBLL();
                DataTable dtUser = userBLL.GetList(sql.ToString()).Tables[0];
                if (dtUser.Rows.Count > 0)
                {
                    //登陆成功
                    Manager.SystemStatus.Instance.User_Role = dtUser.Rows[0]["user_role"].ToString();
                    SaveUserRefer();
                    ret = true;
                }
                return ret;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnOK_Click(sender, e);
            }
        }

        private void txtUserID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtPassword.Focus();
            }
        }
        private void CheckDb()
        {
            try
            {
                if (!DBUtility.DbHelperSQL.TabExists("sys_user"))
                {
                    btnSetDb.Visible = true;
                }
                else
                {
                    btnSetDb.Visible = false;
                }
            }catch(Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }

        private void btnSetDb_Click(object sender, EventArgs e)
        {
            Config.SetDataBase setDb = new Config.SetDataBase();
            setDb.ShowDialog();
        }

        private void txtStation_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnOK_Click(sender, e);
            }
        }
    }
}